<?php
    if ( !empty($_POST)) {
		$nome = $_POST['nome'];		
		$usuario = $_POST['usuario'];
		
		$salt = '1%1cAu!g+>K53PY}';	
		$senha = $_POST['senha'];
		$senha = md5($senha . $salt);
		
		
		$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
        $sql = $pdo->prepare("SELECT * FROM usuarios WHERE usuario='$usuario'");
		$sql->execute();
        $num = $sql->rowCount();	
		
		if($num >0){
            echo "<script>alert('Ops!!! Temos um problema com seu cadastro. Estes dados já está sendo utilizado. Tente novamente!');history.back();</script>";
        }else{
			if ( !empty($_POST)) {	
			$pdo = Database::connect();
			$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$sql = "INSERT INTO usuarios (nome,usuario,senha) values(?,?,?)";
			$q = $pdo->prepare($sql);
			$q->execute(array($nome,$usuario,$senha));	
			Database::disconnect();
			echo '
				<script language>
					$(function(){
						alerta("Cadastro realizado com sucesso!");
					}); 
				</script>
			';
			echo "<meta HTTP-EQUIV='Refresh' CONTENT='1;URL=usuarios'>";
			}
		}
    }
	
    
    /*Script de Paginacao*/
    ini_set('display_errors','On');
    error_reporting(-1);

    require_once('pagination.php');
    if(isset($_GET['page']))
    {
    $page = $_GET['page'];
    }
    else
    {
    $page = 1;
    }
    $options = array(
        'results_per_page' => 6,
        'url' => 'usuarios&page=*VAR*',
        'db_handle' => $dbh
    );
    try
    {
        $paginate = new pagination($page, 'SELECT * FROM usuarios ORDER BY id DESC', $options);
    }
    catch(paginationException $e)
    {
        echo $e;
        exit();
    }

    if($paginate->success == true)
    {
        $result = $paginate->resultset->fetchAll();

    }
?>  
    <div id="page-wrapper">
        <div class="row">
          <div class="col-lg-12">
			<h1><i class="fa fa-users"></i> <?php echo $ssusuarios ?></h1>
          </div>
        </div><!-- /.row -->
      <!-- Button to trigger modal -->
        
            <div class="table-responsive"> 
                    <div style="float:left; padding: 10px 0 10px 0">            
                    <a href="#myModal" role="button" data-toggle="modal" class="btn btn-large btn-success" >
                        <i class="fa fa-users"></i> Add <?php echo $ssusuarios ?>
                    </a>
                    </div>            
                    <div style="float: right; padding: 20px 0 0px 0">
                        Total de <?php echo $paginate->total_results ?> Consulta(s) em <?php echo $paginate->total_pages ?> página(s)
                    </div> 
                  
                  <!-- Modal add Usuários -->
                    <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                      <div class="modal-header">
                          <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-mail-reply-all"></i> Fechar</button>
                        <h3 id="myModalLabel"><i class="fa fa-users"></i> Adicione um novo <?php echo $ssusuarios ?></h3>
                      </div>

                        <form name="signup" method="post" action="usuarios">  
                            <div class="modal-body">
                                
                                <div class="form-group">
                                  <label class="control-label">Nome</label>
                                  <div class="controls">
                                      <input name="nome" type="text" class="form-control" placeholder="Nome" data-required="true" data-pattern="^[a-zA-Z0-9._-]{3,16}" data-describedby="nome" data-description="valida">
                                  </div>
                                  <div id="nome"></div><!--Aparece alerta-->
                                </div>  

                                <div class="form-group">
                                    <label class="control-label">Usuário</label>
                                    <div class="controls">
                                        <input name="usuario" type="text" class="form-control" placeholder="Usuário" data-required="true" data-pattern="^[a-zA-Z0-9._-]{3,16}" data-describedby="usuario" data-description="valida">
                                    </div>
                                    <div id="usuario"></div><!--Aparece alerta-->
                                  </div> 
                                
                                <div class="form-group">
                                    <label class="control-label">Senha</label>
                                    <div class="controls">
                                        <input name="senha" type="password" class="form-control" placeholder="Senha" data-required="true" data-pattern="^[A-Za-z0-9!@#$%^&*()_]{6,16}" data-describedby="senha" data-description="valida">
                                    </div>
                                    <div id="senha"></div><!--Aparece alerta-->
                                  </div>                                 

                            </div>
                            <div class="modal-footer">
                              <button class="btn btn-success"><i class="fa fa-check-circle"></i> Cadastrar</button>
                            </div>
                        </form>

                    </div>
                  <!-- /Modal add Usuários -->
                  
                  <table class="table table-bordered table-hover table-striped tablesorter">
                    <thead>
                      <tr class="success">
                          <th style="text-align:center"><input type="checkbox" onClick="toggle(this)" /></th>
                        <th>Nome</th>
                        <th style="width: 250px">Usuário</th>
                        <th style="width: 250px">Senha</th>
                        <th style="width: 190px">Ações</th>
                      </tr>
                    </thead>
                    <tbody>
                        <form action="helpers/usuarios-del.php" method="post" onSubmit="if(!confirm('Está certo de deletar os itens selecionados?')){return false;}" >
                            <?php foreach ($result as $row):?>    
                              <tr>                          
                                <td align="center" valign="middle"><input name="foo[]" type="checkbox" value="<?php echo $row['id'];?>"  /></td>
                                
                                <td><?php echo $row['nome']; ?></td>
                                <td><?php echo $row['usuario']; ?></td>
                                <td>**********</td>
                                <td>
                                  <a class="btn btn-large btn-primary" href="usuarios-edita&id=<?php echo $row['id']?>"><i class="fa fa-pencil-square-o"></i> Editar</a>
                                  <a class="btn btn-large btn-danger" href="usuarios-del&id=<?php echo $row['id']?>"><i class="fa fa-ban"></i> Excluir</a>                              
                                </td>
                              </tr>
                            <?php endforeach; ?>
                            <td colspan="6">
                                <div style="float: left; padding: 20px 0"><button type="submit" class="btn btn-large btn-danger">Excluir Selecionados</button></div>
                                <div style="float: right"><?php echo $paginate->links_html ?></div>
                            </td>
                         </form>
                    </tbody>
                  </table>

        </div><!-- /.row -->

        

      </div><!-- /#page-wrapper -->

    </div><!-- /#wrapper --> 